package com.edu.robot.modules.im.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.edu.chat.facade.facade.MessageFacade;
import com.edu.chat.facade.model.enums.MsgTypeEnum;
import com.edu.robot.common.service.ChannelManger;
import com.edu.robot.core.enums.NotifyMsgEnum;
import com.edu.robot.core.model.APICallback;
import com.edu.chat.facade.model.dto.SendMessageDTO;
import com.edu.robot.modules.im.service.MessageManger;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-03-30 19:12
 **/

@Service
@Slf4j
public class MessageMangerImpl implements MessageManger {

	@Autowired
	private ChannelManger channelManager;

	@DubboReference(interfaceClass = MessageFacade.class,check = false)
	private MessageFacade messageFacade;

	//新建线程池
	private static final ThreadPoolExecutor executor =
			new ThreadPoolExecutor(5,
			10,
			60,
					TimeUnit.SECONDS,
					new ArrayBlockingQueue<>(1000));


	@Override
	public void sendMessage(SendMessageDTO sendMessageDTO) {

	}

	@Override
	public APICallback sendStreamMessage(final String sessionId, final String userId,final String robotId,final String tenantId) {

		SendMessageDTO sentMessageDTO = new SendMessageDTO();
		sentMessageDTO.setSessionId(sessionId);
		sentMessageDTO.setUserId(userId);
		sentMessageDTO.setRobotId(robotId);
		sentMessageDTO.setTenantId(tenantId);
		sentMessageDTO.setMsgType(MsgTypeEnum.ROBOT.getCode());
		return new APICallback() {

			final String messageId = IdUtil.getSnowflakeNextIdStr();

			@Override
			public void onEvent(NotifyMsgEnum notification, String msg) {

				sentMessageDTO.setMsgType(MsgTypeEnum.ROBOT.getCode());
				// 非正常消息类型
				if(!NotifyMsgEnum.NORMAL.equals(notification)){
					sentMessageDTO.setMsgType(notification.getCode());
				}

				sentMessageDTO.setContent(msg);
				sentMessageDTO.setMessageId(messageId);
				channelManager.sendMessage(userId,messageId, JSONUtil.toJsonStr(sentMessageDTO));
			}

			@Override
			public void close(String finalMsg) {

				sentMessageDTO.setContent(finalMsg);
				sentMessageDTO.setMessageId(messageId);

				//数据落库
				insertMsg(sentMessageDTO);

				SendMessageDTO sentMessage = new SendMessageDTO();
				sentMessage.setSessionId(sessionId);
				sentMessage.setUserId(userId);
				sentMessage.setRobotId(robotId);
				sentMessage.setTenantId(tenantId);
				sentMessage.setMsgType(MsgTypeEnum.ROBOT.getCode());
				sentMessage.setMessageId(messageId);
				sentMessage.setTimestamp(System.currentTimeMillis());
				sentMessage.setContent("[DONE]");
				channelManager.sendMessage(userId,messageId, JSONUtil.toJsonStr(sentMessage));

				//断开sse
				channelManager.closeSse(userId);

			}

			@Override
			public void onError(Exception err) {
				log.error("发送消息异常,异常信息:{}",err.getMessage());
				channelManager.closeSse(userId);
			}
		};


	}

	@Override
	public void insertMsg(SendMessageDTO sendMessageDTO) {
		//异步数据入库
		CompletableFuture.runAsync(()->{
			messageFacade.addMessage(sendMessageDTO);
		},executor);
	}
}
